<div id="upload_body" style="height: 28.8em">
  <div id="form_holder" style="margin:0px; margin-left: 20px">
    <form id="image_form" target="upload_target" method="post" style="margin:0px"
      enctype="multipart/form-data" action="/uploadImage/">
      {% csrf_token %}
      <input type="file" id="image_file" name="image_file" accept="image/*"/>
    </form>
    <iframe id="upload_target" name="upload_target" src="" style="display: none">
	    <script>
				function init() {
				  if(top.ieUploadDone) top.ieUploadDone(); //top means parent frame.
				}
			</script>
    </iframe>
	</div>
  <div id="drag_drop_label" class="label label-info hide" style="margin: 0px; margin-left: 20px;
    width: 393px; opacity:0.3; text-align: center;" class="hide">
    <strong>You can drag and drop an image below</strong>
  </div>
	<div style="margin-top: 5px;margin-bottom: 2px">
		<ul id="image_upload_template" class="thumbnails" style="margin-bottom: 10px;">
		  <li id="image_holder" class="thumbnail" style="margin-bottom: 0px;width: 390px;height: 220px">
		    <img id="upload-image-preview" src="/site_media/images/blank.png"
		    style='width:auto;height: auto;max-height: 220px;max-width: 390px;'>
		  </li>
		</ul>
	</div>
	<div style="margin-left: 20px;">
	  <div id="image-upload-progress" style="width: 400px;margin-bottom: 5px"
	    class="progress progress-info progress-striped">
		  <div id="image-upload-bar" class="bar" style="width: 0%;text-align: center;white-space:nowrap;
		    color: #0088cc; overflow: visible"></div>
	  </div>
	  <div>
	    <button style="width: 130px" id="preview-button" class="btn btn-info dropdown-toggle" disabled="disabled"><i class="icon-eye-open icon-white"></i>&nbspPreview Image</button>
		  <button style="width: 130px" id="discard-button" class="btn btn-warning" disabled="disabled"><i class="icon-remove icon-white"></i>&nbspDiscard Image</button>
		  <button style="width: 130px" id="save-button" class="btn btn-success" disabled="disabled"><i class="icon-ok icon-white"></i>&nbspUse as avatar</button>
	  </div>
	</div>
</div>
<div id="profile_preview_modal" class="hide"
  style="z-index: 1000000; position: absolute; left: 50%; top: 50%; margin-left: -80px;margin-top: -70px;">
  <ul class="thumbnails">
  <li class="thumbnail" style="background-color: white;">
  <div style="color: gray; cursor: move">
    <b>Preview</b>
    <a href="#" style="float:right" onclick="$('#profile_preview_modal').fadeOut('fast');" class="close"><i class="icon-remove icon"></i></a>
  </div>
  <ul class="thumbnails">
    <li id="preview-profile-pic-thumbnail"
      class="thumbnail" style="margin-left: 0px; margin-top: 0px; margin-bottom: 0px; width: 95px; height: 110px;">
      <div class='label-square-bottom label-info username_of_{{ profile.id }}' style='width:90px;padding-right: 2px'>
        {{ profile.name }}
      </div>
      <div style="height: 95px;width: 95px; background-color: gray;overflow: hidden;">
      <img id="preview-profile" style="max-width: 100000%"></img>
      </div>
    </li>
  </ul>
  </li>
  </ul>
</div>
<script>
$(document).ready(function() {
	var imageFile = null;
	var fileName = null;
	var currentImage = null;
	var jcropApi = null;

	initUploads();

	function initUploads(){
		if (awesomeBrowser && firstLoadOfUploadPage) {
			$("#drag_drop_label").show();
			$("#image_holder").attr("rel", "tooltip");
			$("#image_holder").attr("title", "drag and drop an image here");
			bindDragAndDrop("#image_holder");
		}
	}

	function ieUploadDone(){
    loadImage("/site_media/images/uploads/{{ profile.id }}/" + $("#image_file").val().split('\\').pop());
    $("#image-upload-bar").text("Uploaded");
    $("#image-upload-bar").width("100%");
    uploadInProgress = false;
    $("#image_file").removeAttr("disabled");
    $("#save-button").removeAttr("disabled");
    $("#discard-button").removeAttr("disabled");
	}

	function bindDragAndDrop(selector) {
		if (awesomeBrowser) {
			$("#drag_drop_label").show();
			$(selector)[0].addEventListener("dragenter", function(evt){
				if(!uploadInProgress){
					$("#image_holder").addClass("thumbnail-clicked");
				}
				else{
					$("#image_holder").removeClass("thumbnail-clicked");
				}
				evt.stopPropagation();
		    evt.preventDefault();
			},false);

			$(selector)[0].addEventListener("dragleave", function(evt){
		    evt.stopPropagation();
		    evt.preventDefault();
		  },false);

			$(selector)[0].addEventListener("dragover", function(evt){
		    evt.stopPropagation();
		    evt.preventDefault();
			  },false);

			$(selector)[0].addEventListener("drop", function(evt){
				if(!uploadInProgress){
					evt.stopPropagation();
			    evt.preventDefault();
			    var dt = evt.dataTransfer;
			    var files = dt.files;
			    if (files.length == 0) return;

					uploadInProgress = true;
					$("#image_file").attr("disabled", "disabled");
				  $("#image_holder").removeClass("thumbnail-clicked");
				  $("#save-button").attr("disabled", "disabled");
		      $("#discard-button").attr("disabled", "disabled");
		      $("#preview-button").attr("disabled", "disabled");
			    handleFiles(files);
				}
		  },false);
		}
	}

	if(firstLoadOfUploadPage){
		$("#image_file").unbind("change");
	  $("#image_file").bind("change", function(evt){
		  uploadInProgress = true;
		  $("#save-button").attr("disabled", "disabled");
      $("#discard-button").attr("disabled", "disabled");
      $("#preview-button").attr("disabled", "disabled");
		  imageSelectedEvent(evt);
	  });
	}

	function imageSelectedEvent(evt) {
     if(awesomeBrowser) {
       var files = evt.target.files; // FileList object
       $("#image_file").attr("disabled", "disabled");
       handleFiles(files);
     }
     else {
    	 $("#image_form").unbind("submit");
    	 $("#image_form").bind("submit", function(){
         formBinding($("#image_form"));
         fileName = $("#image_file").val().split('\\').pop();
       });
       $("#image_form").submit();
       $("#image_file").attr("disabled", "disabled");
     }
	}

	function formBinding(oldForm){
		$("#image-upload-bar").text("Uploading");
		$("#image-upload-bar").width("50%");

		$("#upload_target").unbind("load");
		$("#upload_target").bind("load", function(evt) {
	    ieUploadDone();
	  });
		setTimeout(fakeUploadProgress, 1000);
	}

	function fakeUploadProgress(){
		if($("#image-upload-bar").width() < 390){
			$("#image-upload-bar").width($("#image-upload-bar").width() + 5);
		  setTimeout(fakeUploadProgress, 1000);
		}
	}

	window.firstLoadOfUploadPage = false;

	function handleFiles(files) {

    // Only process image files.
    if(files.length == 0) {
    	uploadInProgress = false;
    	return;
    }
    f = files.item(0);
    if (!f.type.match('image.*')) {
    	uploadInProgress = false;
      return;
    }

    imageFile = f;
    fileName = f.name;
    var reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = (function(theFile) {
      return function(e) {
        loadImage(e.target.result);
        uploadImageFile();
      };
    })(f);
    // Read in the image file as a data URL.
    reader.readAsDataURL(f);
	}

	function loadImage(src) {
		var image = $("#upload-image-preview");
		image.attr("src", src);
    addJcropToImage(image);
	}

	function addJcropToImage(image) {
		$(".jcrop-holder").show();
		image.unbind('load');
		image.bind('load', function() {
			$("#preview-button").removeAttr("disabled");
			if(image.attr("src") == "/site_media/images/blank.png" || image.attr("src") == currentImage){
				return;
	    }

			currentImage = image.attr("src");
			if(jcropApi == null) {
				jcropApi = $.Jcrop(image, {
					aspectRatio: 1,
					setSelect: [0, 0, image.width(), image.height()], onChange: updatePreview, onSelect: updatePreview});
		  }
			else {
				jcropApi.setImage(image.attr("src"), function(){
				  image.height("auto");
					image.width("auto");
					jcropApi.setOptions({ maxSize: [ image.width(), image.height() ], bgOpacity: 0.4 });
					jcropApi.setSelect([0, 0, image.width(), image.height()]);
					$(".jcrop-tracker").width(image.width());
					$(".jcrop-tracker").height(image.height());
					$("#image_holder").find("div").css("background-color", "");
					if($("#profile_preview_modal").is(":visible")) {
						showPreview();
					}
				});
			}
     });
	}

	function uploadImageFile(){
    if(awesomeBrowser) {
			$("#image-upload-bar").width("0%");
	    var xhr = new XMLHttpRequest();
	    var total = 0;
	    xhr.upload.addEventListener("progress", function(evt) {
	      evt.target.curLoad = evt.loaded;
	      total = evt.total;
	      $("#image-upload-bar").width((evt.loaded * 100)/evt.total + "%");
	      $("#image-upload-bar").text(Math.round(evt.loaded/1000) + " of " + Math.round(evt.total/1000) + "KB");

	    }, false);
	    xhr.upload.addEventListener("load", function(evt){
	    	$("#image-upload-bar").width("100%");
	    	$("#image-upload-bar").text(Math.round(total/1000) + " of " + Math.round(total/1000) + "KB");
	    	uploadInProgress = false;
	    	$("#image_file").removeAttr("disabled");
	    	$("#save-button").removeAttr("disabled");
        $("#discard-button").removeAttr("disabled");
	    }, false);
	    sendImageUpload(xhr);
    }
	}

	function sendImageUpload(xhr){
		var formData = new FormData();
    formData.append("image_file", imageFile);
    formData.append("csrfmiddlewaretoken", '{{ csrf_token }}');
    xhr.open("POST", "/uploadImage/");
    xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
    xhr.setRequestHeader("enctype", "multipart/form-data");
    xhr.send(formData);
	}

	if (!$("#preview-button").data('events').click) {
		$("#preview-button").click(function(){
			showPreview();
		});
	}

	if (!$("#discard-button").data('events').click) {
    $("#discard-button").click(function(){
    	$("#upload-image-preview").attr("src", "/site_media/images/blank.png")
      $("#image_form").val("");
    	$("#save-button").attr("disabled", "disabled");
      $("#discard-button").attr("disabled", "disabled");
      $("#preview-button").attr("disabled", "disabled");
      $(".jcrop-holder").hide();
      $("#profile_preview_modal").hide();
      $("#image_form")[0].reset();
    });
  }

	if (!$("#save-button").data('events').click) {
    $("#save-button").click(function(){
    	$(this).attr("disabled", "disabled");
    	coords = jcropApi.tellSelect();
    	 $.post("/setAvatarFromUpload/", {
				"file_name": fileName,
				"x1": coords.x,
				"x2": coords.x2,
				"y1": coords.y,
				"y2": coords.y2,
				"image_width": $("#upload-image-preview").width(),
				"image_height": $("#upload-image-preview").height()
    	})
    	.success(function(){
    		sendProfileUpdate("avatar",
    				"{{ profile.getAvatar }}",
    				"/site_media/images/uploads/{{ profile.id }}/custom_avatar.png?" + new Date().getTime());
    		$("#save-button").removeAttr("disabled");
    	})
      .error(function(){
    	  alert("Failed to set image. Please try again");
    	  $("#save-button").removeAttr("disabled");
      });
    });
  }

	function showPreview() {
		if($("#preview-profile").attr("src") == $("#upload-image-preview").attr("src")){
			$("#profile_preview_modal").fadeIn("fast");
		}
		$("#preview-profile").attr("src", $("#upload-image-preview").attr("src"));
	  $("#preview-profile").load(function(){
		  coords = jcropApi.tellSelect();
		  updatePreview(coords);
		  $("#profile_preview_modal").fadeIn("fast");
		  $("#profile_preview_modal").draggable();
	  });
	}

	function updatePreview(coords) {
		var rx = 95 / coords.w;
	  var ry = 95 / coords.h;

	  $('#preview-profile').width(Math.round(rx * $('#upload-image-preview').width()) + 'px');
	  $('#preview-profile').css({
	    width: Math.round(rx * $('#upload-image-preview').width()) + 'px',
	    height: Math.round(ry * $('#upload-image-preview').height()) + 'px',
	    marginLeft: '-' + Math.round(rx * coords.x) + 'px',
	    marginTop: '-' + Math.round(ry * coords.y) + 'px'
	  });
	}

	function sendProfileUpdate(field, oldValue, newValue) {
    var mex = "PLAYER_PROFILE_UPDATES|{{ profile.id }}|" + field + "|" + oldValue + "|" +
    newValue + "|{{ profile.getActiveGameIds }}";
    engineRef.sendMessage(mex, null, 5000);
  }

});
</script>